<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { useCustomCountdown } from '@/hook/useCountDown';
import { rules } from '@/utils/rule';
import { request } from "@/service/request";
import API from "@/service/api/order";

// 定义组件Props
const props = defineProps<{
    phoneNumber?: string;
    placeholder?: string;
    maxlength?: number;
    sendText?: string;
    requiredPhone?: boolean;
    customValidator?: (phone: string) => boolean;
    code?: string;
}>();

// 定义组件Emits
const emits = defineEmits<{
    (e: 'update:code', value: string): void;
    (e: 'send', phone: string): Promise<boolean>;
}>();

// 本地状态管理
const placeholder = ref(props.placeholder || '请输入验证码');
const sendText = ref(props.sendText || '发送验证码');
const maxlength = ref(props.maxlength || 6);

// 倒计时功能
const { remaining, startCountdown, counting } = useCustomCountdown({
});

// 计算属性：是否可以发送验证码
let phoneReg = rules.phone[1].pattern;
const canSend = computed(() => {
    if (!props.phoneNumber && props.requiredPhone !== false) return false;
    if (props.customValidator) return props.customValidator(props.phoneNumber || '');
    return phoneReg?.test(props.phoneNumber || '');
});

// 处理验证码输入
const code = computed({
    get() {
        return props.code || '';
    },
    set(value) {
        emits('update:code', value);
    }
});
const handleCodeInput = (value: string) => {
};

//发送验证码
const clkSendCode = async (phoneNumber: string): Promise<boolean> => {
  try {
    await request.post<any>(API.sendSms, {phone: phoneNumber});
    startCountdown(60);
    showToast('验证码发送成功');
    return true;
  }catch (error) {
    return false;
  }
};
// 处理发送验证码
const handleSendCode = async () => {
    if (!canSend.value || !props.phoneNumber) return;
    try {
       clkSendCode(props.phoneNumber);
    } catch (error) {
        console.log(error);
        
    }
};

// 监听props变化更新本地变量
watch(
    () => props.placeholder,
    (val) => {
        placeholder.value = val || '请输入验证码';
    }
);

watch(
    () => props.sendText,
    (val) => {
        sendText.value = val || '发送验证码';
    }
);

watch(
    () => props.maxlength,
    (val) => {
        if (val) maxlength.value = val;
    }
);
</script>


<template>
    <div class="verification-code-container flex items-center gap-2">
        <cVanfield v-model="code" type="text" :placeholder="placeholder" :maxlength="maxlength" @input="handleCodeInput"
            class="flex-1">
            <template #button>
                <cButton :disabled="counting || !canSend" @click="handleSendCode"
                    class="send-code-btn whitespace-nowrap font-normal"   iColor="rgba(255, 0, 0, 0.6)" iFontSize="4vmin">
                    {{ counting ? `${remaining}秒后重新发送` : sendText }}
                </cButton>
            </template>
        </cVanfield>
    </div>
</template>


<style scoped lang="scss">
.verification-code-container {
    width: 100%;

    :deep(.van-field__control) {
        padding:0px;
    }

    :deep(.van-field__button) {
        padding-left: 0px;
    }
}

.send-code-btn {
    min-width: 120px;
}
</style>